<?php

namespace addons\booking\model;

use addons\booking\model\StoreOrder as StoreOrderModel;
use think\Model;
use addons\booking\model\Store as StoreModel;
use addons\booking\model\StoreBill;
use addons\booking\model\OrderFirst;
use addons\booking\model\StoreOrderSon as StoreOrderSonModel;
use think\Db;

class StoreOrderSon extends Model
{

    // 表名
    protected $name = 'store_order_son';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [];

    public static function uni_order_sn()
    {
        //日期
        $order_date = date('Y-m-d');
        //订单号主体
        $order_id_main = date('YmdHis') . rand(10000000,99999999);
        //订单号长度
        $order_id_len = strlen($order_id_main);
        $order_id_sum = 0;
        for($i=0; $i<$order_id_len; $i++){
            $order_id_sum += (int)(substr($order_id_main,$i,1));
        }
        //唯一订单号
        $order_sn = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100,2,'0',STR_PAD_LEFT);
        return $order_sn;
    }

    //抢单大厅
    public static function order_hall($worker_id,$page,$limit,$latitude,$longitude,$condition)
    {
        $workerInfo = Worker::where('id',$worker_id)->find();
        // 数据库字段名 - 纬度
        $field_lat = 'latitude';
        // 数据库字段名 - 经度
        $field_lng = 'longitude';

        $where['a.status'] = "0";
        if($condition['store_id'] >0 ){
            $where['a.store_id'] = $condition['store_id'];
        }
        if($condition['end_distance'] >0 ){
//            $where['distance'] = ['between',[$condition['start_distance'],$condition['end_distance']]];
        }
        if($condition['order_date'] > 0){
            $where['a.arrival_date'] = $condition['order_date'];
        }
        if($condition['time_key'] > 0){
            $where['a.time_key'] = $condition['time_key'];
        }

        $mainQuery = Db::table('nn_store_order')->alias('m');
        $list = StoreOrderModel::alias('a')
            ->with([
                'Store' => function ($query) {
                    $query->field('id,name,logo,address,phone');
                },
                'First' => function ($query) use ($worker_id)  {
                    $query->where('worker_id',$worker_id)->where('status',0)->field('id,order_id,status');
                },
            ])
            ->where(function ($query) use ($worker_id,$mainQuery){
                $order = $mainQuery->field('id,worker_num')->find();
                $order_id = $order['id'];
                //已接单的保洁就抢单大厅不显示
                $order_ids = $query->table('nn_store_order_son')->where('worker_id',$worker_id)->where('order_id',$order_id)->where('status','in',[1,2,3,4])->value('order_id');
                if($order_ids){
                    $query->where('id','!=',$order_ids);
                }
//                $worker_num = $order['worker_num'];
//                //已接单数
//                $worker_ids = $query->table('nn_store_order_son')->where('order_id',$order_id)->where('status','in',[1,2,3,4])->column('worker_id');
//                $received_num = count($worker_ids);
//                $first_num = $query->table('nn_order_first')->where('order_id',$order_id)->where('status','in',[0,1])->count();
//                $total_num = $received_num + $first_num;
            })
            ->field("a.id,a.status,a.costs_total_price,a.add_price,a.urgent_price,a.mark,a.arrival_time,a.arrival_date,a.room_num,a.worker_num,a.store_id,(6378.138 * 2 * asin(sqrt(pow(sin(({$field_lat} * pi() / 180 - {$latitude} * pi() / 180) / 2),2) + cos({$field_lat} * pi() / 180) * cos({$latitude} * pi() / 180) * pow(sin(({$field_lng} * pi() / 180 - {$longitude} * pi() / 180) / 2),2))) * 1000) as distance")
            ->where($where)
            ->order(['distance'=>'desc','urgent_price'=>'desc','add_price'=>'desc'])
            ->select();

         $list =  collection($list)->toArray();

         foreach ($list as $k=>$v){
             $list[$k]['order_son_num'] = Db::name('store_order_son')->where('order_id',$v['id'])->where('status','in',[1,2,3,4])->count();
             $list[$k]['arrival_day'] = check_time($v['arrival_time']);
             $distance =  number_format($v['distance'] / 1000, 1);
             $list[$k]['distance'] = $distance;
         }

         return $list;

    }

    //拒绝接单
    public static function refuse_order($worker_id=0,$order_id=0)
    {
        $order = StoreOrderModel::where('id',$order_id)->find();
        if($order['status'] != 1){
            return ['status'=>-1,'msg'=>'该订单状态无法操作'];
        }
        $order_son = OrderFirst::where('worker_id',$worker_id)->where('order_id',$order_id)->find();

        $map['status'] = 2;
        $map['lose_time'] = time();
        $res = OrderFirst::where('id',$order_son['id'])->update($map);
        if($res){
            return ['status'=>1,'msg'=>'操作成功'];
        } else {
            return ['status'=>-1,'msg'=>'操作失败'];
        }
    }

    //接受订单
    public static function accept_order($worker_id=0,$order_id=0)
    {
       Db::startTrans();
        try {
            $order = StoreOrderModel::where('id', $order_id)->lock(true)->find();
            if($order['status'] != 1)  return ['status'=>-1,'msg'=>'该订单状态无法接单'];
            $order_son_num = self::where('order_id', $order_id)->where('status','in',[1,2,3,4])->count();
            if($order_son_num >= $order['worker_num'])  return ['status'=>-1,'msg'=>'该订单已匹配满'];
            $order_son = self::where('order_id',$order_id)->where('worker_id',$worker_id)->where('status','in',[1,2,3,4])->find();
            if($order_son)  return ['status'=>-1,'msg'=>'请勿重复接单'];
            //增加子订单
            $insert['order_id'] = $order_id;
            $insert['worker_id'] = $worker_id;
            $insert['status'] = 1;
            $insert['create_time'] = time();
            $res = self::insert($insert);

            //更新优先指派
            $fisrt = OrderFirst::where(['order_id'=>$order_id,'worker_id'=>$worker_id,'status'=>0])->find();
            if($fisrt){
                OrderFirst::where('id',$fisrt['id'])->update(['status'=>1]);
            }

            $order_update['worker_num'] = $order['worker_num'] + 1;
            //更新订单状态
            if(($order_son_num+1) >= $order['worker_num']){
                $order_update['status'] = 1;
            }
            StoreOrderModel::where('id', $order_id)->update($order_update);

            Db::commit();
            return ['status'=>1,'msg'=>'接单成功'];
        }catch(\Exception $e){
            Db::rollback();
            return ['status'=>-1,'msg'=>'接单失败'];
        }

    }

    //已接单保洁列表
    public  static function receiving_worker($order_id)
    {
        $where['s.order_id'] = $order_id;
        $where['s.status'] = ['<',"5"];
        $list = self::alias('s')
            ->join('store_order o','s.order_id=o.id','left')
            ->join('worker w','s.worker_id=w.id','left')
            ->field('s.id,s.order_id,s.worker_id,o.order_sn,o.arrival_time,w.user_name,w.head_image')
            ->where($where)
            ->select();
        foreach ($list as $k=>$v){
            $list[$k]['order_son_num'] = Db::name('order_room')->where('order_id',$order_id)->where('status','<',5)->count();
            $list[$k]['arrival_time'] = date('h:i',$v['arrival_time']);
            $list[$k]['max_num'] = 10;
        }

        return $list ? $list :[];
    }

    public function StoreUser()
    {
        return $this->belongsTo('\addons\booking\model\StoreUser', 'store_user_id', 'id');
    }

    //优先指派
    public function Fisrt()
    {
        return $this->hasOne('OrderFirst', 'order_id', 'id');
    }

    //优先指派
    public function Store()
    {
        return $this->belongsTo('StoreOrder', 'order_id', 'id');
    }

}
